var common_channel = "/topic/common/message";
var private_channel = "/user/topic/private/message";
var room_channel = "/app/topic/room";
var transfer_channel = "/app/topic/transfer-msg";

var notic = ["系统公告"];

var subscription = null;

var ws = new SockJS("./marcopolo");
var stomp = Stomp.over(ws);

stomp.connect({},connect_success,connect_error);

function connect_success(frame){
	console.log("连接成功");
	//订阅公共信息源
	stomp.subscribe(common_channel,handleCommonMessage);
}

function connect_error(err){
	console.log("连接出错",err);
}

function sendMsg(addr,msg){
	stomp.send(addr,{},JSON.stringify({"message":msg}));
}

/**
 *信息中转
 */
function transferMsg(msg){
	stomp.send(transfer_channel,{},JSON.stringify({"message":msg}));
}

/**
 * 加入房间
 */
function enterRoom(){
	//订阅房间频道
	//private_channel暂时当作房间
	subscription = stomp.subscribe(private_channel,handlePrivateMessage);
	console.info("订阅描述符：",subscription);
	//发送加入房间指令
	stomp.send(room_channel);
}

/**
 * 公共信息处理
 */
function handleCommonMessage(message){
	console.log("handleCommonMessage",message);
	notic.push(message.body);
}

/**
 * 私人信息处理
 */
function handlePrivateMessage(message){
	console.log("handlePrivateMessage",message);
	var msg = message.body;
	switch(msg){
	case 'wait':
		alert("当前频道没有人，请稍后");
		break;
	case 'full':
		alert("房间已满");
		break;
	case 'join':
		doCall();
		break;
	case 'end':
		closeWebRTC();
		break;
	default:
		react = JSON.parse(msg);
		switch(react.type){
		case 'offer':
			//如果不是创造者的话，接收offer
			console.log("收到 offer 收到 offer 收到 offer");
			pc.setRemoteDescription(new RTCSessionDescription(react));
			//同时返回应答
			doAnswer();
			break;
		case 'answer':
			console.log("收到 answer 收到 answer 收到 answer");
			pc.setRemoteDescription(new RTCSessionDescription(react));
			break;
		case 'candidate':
			console.log("收到 candidate 收到 candidate 收到 candidate");
			var candidate = new RTCIceCandidate({
				sdpMLineIndex:react.label,
				sdpMind:react.id,
				candidate:react.candidate
			});
			pc.addIceCandidate(candidate).then(function(e){
				console.log("成功添加ice candidate",e);
			}).catch(function(e){
				console.log(e);
			});
			break;
		}
		break;
	}
}